import Icon from '@/components/Icon'
import { useInitialState } from '@/utils/hooks'
import { NavBar, Input, Toast } from 'antd-mobile'
import { useEffect, useRef, useState } from 'react'
import { useHistory } from 'react-router-dom'
import styles from './index.module.scss'
import { getUserProfile } from '@/store/actions/profile'
import io, {Socket} from 'socket.io-client'
import { getToken } from '@/utils/storage'

const Chat = () => {
  const history = useHistory()
  const [messageList, setMessageList] = useState<{
    type: 'robot' | 'user'
    text: string
  }[]>([
    {type: 'robot', text: '亲爱的用户您好，小智同学为您服务。'},
  ])

  const [message, setMessage] = useState('')

  const {userProfile} = useInitialState(getUserProfile, 'profile');

  const clientRef = useRef<Socket | null>(null);

  const listRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const client = io('http://geek.itheima.net/', {
      query: {
          token: getToken().token
      },
      transports: ['websocket']
    })

    client.on('connect', ()=> {
      Toast.show('建立连接成功')
    })

    client.on('message', (data) => {
      setMessageList((messageList) => [
        ...messageList,
        {
          type: 'robot',
          text: data.msg
        }
      ])
    })

    clientRef.current = client;

    return () => {
      // 主动关闭和服务器的链接
      client.close();
    }

  }, [])

  // 监听聊天数据的变化，改变聊天容器元素的 scrollTop 值让页面滚到最底部
  useEffect(() => {
    const current = listRef.current!
    current.scrollTop = current.scrollHeight
  }, [messageList])

  const onSubmit = (e: React.KeyboardEvent<HTMLInputElement>) => {
    //当按回车时，发送信息
    if (e.key === 'Enter' && message) {
      clientRef.current!.emit('message', {
        msg: message,
        timestamp: Date.now()
      })
      setMessageList((messageList) => [...messageList, {
        type: 'user',
        text: message
      }])
      setMessage('')
    }
  }

  return (
    <div className={styles.root}>
      {/* 顶部导航栏 */}
      <NavBar className="fixed-header" onBack={() => history.go(-1)}>
        小智同学
      </NavBar>

      {/* 聊天记录列表 */}
      <div ref={listRef} className="chat-list">
        {messageList.map((msg, index) => {
          if (msg.type === 'robot') {
            return (
              // {/* 机器人的消息 */}
              <div className="chat-item" key={index}>
                <Icon type="iconbtn_xiaozhitongxue" />
                <div className="message">{msg.text}</div>
              </div>
            )
          } else {
            return (
              // {/* 用户的消息 */}
              <div key={index} className="chat-item user">
                <img src={userProfile.photo} alt="" />
                <div className="message">{msg.text}</div>
              </div>
            )
          }
        })}
      </div>

      {/* 底部消息输入框 */}
      <div className="input-footer">
        <Input
          className="input no-border"
          placeholder="请描述您的问题"
          value={message}
          onChange={value => setMessage(value)}
          onKeyUp={onSubmit}
        />
        <Icon type="iconbianji" />
      </div>
    </div>
  )
}

export default Chat
